package com.shop.shopserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shop.shopcommon.exception.Base.PrivilegesNotFoundException;
import com.shop.shopcommon.exception.Base.SmsCodeNotFoundException;
import com.shop.shopcommon.token.CustomUser;
import com.shop.shoppojo.entity.User;
import com.shop.shopserver.mapper.UserMapper;
import com.shop.shopserver.service.PhoneUserDetailsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.shop.shopcommon.constant.MessageConstant.*;
import static com.shop.shopcommon.constant.RedisConstant.USER_VERIFICATION_CODE_KEY;

/**
 * 手机号验证码登录认证
 */
@Service
@Slf4j
public class PhoneUserDetailsServiceImpl implements PhoneUserDetailsService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private UserMapper userMapper;
    public CustomUser loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("进入验证码认证");
        // 判断username是否为空
        if (username == null || username.isEmpty()){
            throw new UsernameNotFoundException(USER_NOT_LOGIN);
        }
        // 拼接redis key 查询验证码
        String key= USER_VERIFICATION_CODE_KEY + username;
        String code = redisTemplate.opsForValue().get(key);
        // 判断验证码是否为空
        if (code == null || code.isEmpty()){
            // 为空抛出异常
            throw new SmsCodeNotFoundException(VERIFICATION_CODE_NOT_NULL);
        }
        // 获取当前登录用户信息
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new QueryWrapper<User>().lambda();
        userLambdaQueryWrapper.eq(User::getUsername, username)
                .select(User::getId, User::getUsername, User::getPassword, User::getValid);
        User user = userMapper.selectOne(userLambdaQueryWrapper);
        if (user == null) {
            //如果用户查不到，返回null，会抛出异常
            throw new UsernameNotFoundException(USER_NOT_EXISTS +":" + username);
        }

        //根据用户id查询用户权限
        List<String> privileges = userMapper.findPrivilegesByUserId(user.getId());
        //将privileges转成数组
        String[] privilegeArray = new String[privileges.size()];
        privileges.toArray(privilegeArray);
        if (privileges.isEmpty()){
            throw new PrivilegesNotFoundException(PRIVILEGES_NOT_FOUND +":" + username);
        }

        // 将权限列表转换为GrantedAuthority集合
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String privilege : privileges) {
            authorities.add(new SimpleGrantedAuthority(privilege));
        }

//        UserDetails userDetails = CustomUser.customBuilder()
//                .withId(user.getId())
//                .withUsername(user.getUsername())
////                .password(code)
//                .withPassword(code)
//                .disabled(!user.getValid())
//                .authorities(privilegeArray).build();
        // 返回自定义的UserDetails
        CustomUser userDetails = new CustomUser(user.getUsername(), code, true, true, true, true, authorities, user.getId());

        log.info("userDetails = " + userDetails);
        return userDetails;
    }
}
